import React from 'react';
import { Form, Input, Button, Typography, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import { useDispatch, useSelector } from 'react-redux';
import { loginStart, loginSuccess, loginFailure } from '../store/slices/userSlice';
import { AppDispatch, RootState } from '../store';
import { useNavigate, Link } from 'react-router-dom';
import api from '../services/api'; // 导入 api 服务

const { Title } = Typography;

const LoginContainer = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
`;

const LoginFormWrapper = styled.div`
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
`;

const StyledButton = styled(Button)`
  width: 100%;
`;

const LoginPage: React.FC = () => {
    const dispatch = useDispatch<AppDispatch>();
    const { loading, isAuthenticated } = useSelector((state: RootState) => state.user);
    const navigate = useNavigate();

    // 如果已认证则重定向
    React.useEffect(() => {
        if (isAuthenticated) {
            navigate('/'); // 重定向到首页
        }
    }, [isAuthenticated, navigate]);

    const onFinish = async (values: any) => {
        dispatch(loginStart());
        try {
            const response = await api.auth.login(values.username, values.password);

            if (response.success && response.user) {
                dispatch(loginSuccess(response.user));
                if (response.token) {
                    localStorage.setItem('userToken', response.token);
                }
                message.success('登录成功！');
            } else {
                const errorMessage = response.message || '登录失败，请重试';
                dispatch(loginFailure(errorMessage));
                message.error(errorMessage);
            }
        } catch (err: any) {
            console.error('Login error:', err);
            const errorMessage = err.response?.data?.message || '登录失败，请重试';
            dispatch(loginFailure(errorMessage));
            message.error(errorMessage);
        }
    };

    return (
        <LoginContainer>
            <LoginFormWrapper>
                <Title level={2} style={{ textAlign: 'center', marginBottom: 32 }}>
                    用户登录
                </Title>
                <Form
                    name="login"
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                >
                    <Form.Item
                        name="username"
                        rules={[{ required: true, message: '请输入用户名' }]}
                    >
                        <Input prefix={<UserOutlined />} placeholder="用户名" />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        rules={[{ required: true, message: '请输入密码' }]}
                    >
                        <Input.Password prefix={<LockOutlined />} placeholder="密码" />
                    </Form.Item>

                    <Form.Item>
                        <StyledButton type="primary" htmlType="submit" loading={loading}>
                            登录
                        </StyledButton>
                    </Form.Item>

                    <div style={{ textAlign: 'center' }}>
                        还没有账号？ <Link to="/register">立即注册</Link>
                    </div>

                </Form>
            </LoginFormWrapper>
        </LoginContainer>
    );
};

export default LoginPage; 